package com.base.monitor.module.biz.mq;

import com.base.monitor.module.biz.properties.ParamProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.jms.*;

/**
 * @author yuel
 * @date 2021/3/5 - 15:09
 */

//队列消息生产者
@Slf4j
@Component
@RefreshScope
@EnableConfigurationProperties(ParamProperties.class)
public class MonitorQueueProducer {

    private Session session = null;
    private Connection connection = null;
    private MessageProducer producer = null;

    /**
     * 初始化生产者
     * @param url activemq地址
     * @param name 队列名称
     */
    public void doInit(String url, String name) {
        try {
            ActiveMQConnectionFactory activeMqConnectionFactory = new ActiveMQConnectionFactory(url);
            connection = activeMqConnectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue(name);
            producer = session.createProducer(destination);
            log.info("activemq生产者初始化成功");
        } catch (JMSException e) {
            log.error("activemq生产者初始化失败，原因是：{}", e.getMessage());
        }

    }

    /**
     * 发送消息
     * @param message 消息内容
     */
    public void sendTextMessage(String message) {
        try {
            TextMessage textMsg = session.createTextMessage(message);
            producer.send(textMsg);
        } catch (JMSException e) {
            if (e.getMessage().equals("The session is closed")) {
                try {
                    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                } catch (JMSException e1) {
                    log.error("重启session失败，原因是：{}", e1.getMessage());
                }
            }
            log.error("activemq生产者消息发送失败，原因是：{}", e.getMessage());
        }
    }

    /**
     * 关闭生产者
     */
    public void closeProducer() {
        try {
            if (producer != null) {
                producer.close();
                producer = null;
            }
            if (session != null) {
                session.close();
                session = null;
            }
            if (connection != null) {
                connection.close();
                connection = null;
            }
            log.info("成功关闭activemq生产者");
        } catch (JMSException e) {
            log.error("关闭activemq生产者失败，原因是：{}", e.getMessage());
        }

    }
}
